<!--
 * @Descripttion: 
 * @version: 
 * @Author: xcb
 * @Date: 2021-04-02 10:24:14
 * @LastEditors: yangyongtao
 * @LastEditTime: 2024-03-14 18:00:22
-->
<template>
  <el-row style="height: 100%" v-if="multipleSelection.length > 0">
    <div class="close">
      <el-icon @click="click"><CircleClose /></el-icon>
    </div>
    <el-col :span="18" style="height: 100%">
      <div
        v-show="searchData.showType != 'tj'"
        id="charts"
        style="width: 100%; height: 100%"
      ></div>
      <div
        v-show="searchData.showType === 'tj'"
        style="width: 100%; height: 100%"
      >
        <el-table
          v-if="tableData.length != 0 && searchData.resultShowType === 'table'"
          size="small"
          :rowKey="(record) => record.key"
          :data="tableData"
          border
          stripe
        >
          <el-table-column
            v-for="(item, i) in tjColumns"
            :key="i"
            :prop="item.dataIndex"
            :label="item.title"
            align="center"
          >
            <template v-if="item.children">
              <el-table-column
                v-for="(ele, k) in item.children"
                :key="k"
                :prop="ele.dataIndex"
                :label="ele.title"
                align="center"
              />
            </template>
            <template v-if="!item.children" #default="scope">
              {{ scope.row[item.dataIndex] }}
            </template>
          </el-table-column>
        </el-table>
        <div v-else id="tjBarEcharts" style="width: 100%; height: 100%"></div>
      </div>
    </el-col>
    <el-col :span="6" style="height: 100%">
      <div class="form">
        <el-form :model="searchData" label-width="120px">
          <el-form-item label="显示类型">
            <el-select
              style="width: 100%"
              v-model="searchData.showType"
              @change="(value) => showTypeChange(value)"
            >
              <el-option
                v-for="(item, i) in typeList"
                :key="i"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-divider />

          <div v-if="searchData.showType != 'tj'">
            <div v-if="searchData.showType === 'dd'">
              <el-form-item label="要素">
                <el-select v-model="searchData.type" @change="getSite">
                  <el-option
                    v-for="(item, i) in optionList"
                    :key="i"
                    :value="item.value"
                    :label="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="站点">
                <el-select v-model="searchData.stcd" @change="search">
                  <el-option
                    v-for="(item, i) in siteList"
                    :key="i"
                    :value="item"
                    :label="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="验证数据">
                <el-checkbox-group v-model="searchData.checkedList">
                  <el-checkbox
                    v-for="(item, i) in ['报汛数据', '整编数据']"
                    :key="i"
                    :label="item"
                  >
                    {{ item }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>

            <div v-if="searchData.showType === 'yc'">
              <el-form-item label="要素">
                <el-select v-model="searchData.type" @change="search">
                  <el-option
                    v-for="(item, i) in optionList"
                    :key="i"
                    :value="item.value"
                    :label="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="河流">
                <el-select v-model="searchData.riverNm" @change="search">
                  <el-option
                    v-for="(item, i) in riverList"
                    :key="i"
                    :value="item"
                    :label="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="时间段">
                <el-slider
                  style="margin: 0 20px"
                  v-model="searchData.timeSelect"
                  :marks="timeList"
                  :max="sliderMax - 1"
                  :show-stops="false"
                  :format-tooltip="formatTooltip"
                  @change="search"
                />
                <div>
                  {{ sliderTimeList.startTime[0] }}~{{
                    sliderTimeList.endTime[0]
                  }}
                </div>
              </el-form-item>
              <el-form-item
                label="播放"
                v-show="searchData.timeType === 'timer'"
              >
                <div
                  style="font-size: 30px; text-align: center; line-height: 0"
                >
                  <BackwardOutlined @click="playNumberChange('add')" />
                  <CaretRightOutlined
                    v-if="!playType"
                    style="margin: 0 15px"
                    @click="playStart(true)"
                  />
                  <PauseOutlined
                    v-else
                    style="margin: 0 15px"
                    @click="deleteInterval(true)"
                  />
                  <ForwardOutlined @click="playNumberChange('less')" />
                </div>
                <div
                  style="user-select: none; float: right; margin-right: 15px"
                >
                  播放间隔：{{ playNumber }}S
                </div>
              </el-form-item>
            </div>
          </div>

          <div v-else>
            <el-form-item label="方案类型">
              <el-select
                style="width: 100%"
                v-model="searchData.resultType"
                @change="(value) => ((tableData = []), search())"
              >
                <el-option value="xqsf" label="汛期沙峰排沙"></el-option>
                <el-option value="xlqkw" label="消落期库尾减淤"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据展示类型">
              <el-select
                style="width: 100%"
                v-model="searchData.resultShowType"
                @change="search"
              >
                <el-option value="table" label="表格"></el-option>
                <el-option value="barEcharts" label="柱状图"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="时间选择">
              <el-slider
                style="margin: 0 20px"
                v-model="searchData.tjTime"
                :marks="timeList"
                range
                :max="sliderMax - 1"
                :format-tooltip="formatTooltip"
                @change="search"
              />
              <div>
                {{ sliderTimeList.startTime[0] }}~{{
                  sliderTimeList.endTime[0]
                }}
              </div>
            </el-form-item> -->
          </div>
        </el-form>
        <el-button
          v-if="searchData.showType != 'tj'"
          class="exportBtn"
          type="primary"
          @click="exportBtn"
        >
          导出
        </el-button>
        <el-button class="btn" type="primary" @click="search">查询</el-button>
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  provide,
  watch,
  reactive,
  toRefs,
  inject,
  // defineEmits,
} from "vue";
import * as echarts from "echarts";

import {
  getSingleAttribute,
  getAloneLine,
  getJyDiaoDuList,
  getPsDiaoDuList,
  exportwriteexcel,
  ycwriteexcel,
  validateReal,
  validateZB,
  readResultFile,
} from "../request/api";
import moment, { Moment } from "moment";
import { ElMessage } from "element-plus";

import {
  BackwardOutlined,
  CaretRightOutlined,
  ForwardOutlined,
  PauseOutlined,
} from "@ant-design/icons-vue";

export default defineComponent({
  name: "ResultPage",
  components: {
    BackwardOutlined,
    CaretRightOutlined,
    ForwardOutlined,
    PauseOutlined,
  },
  setup() {
    const searchData = reactive({
      plannos: "",
      showType: "yc",
      resultShowType: "table",
      type: "水位",
      timeSelect: "",
      tjTime: [],
      resultType: "xqsf",
      timeType: "timep",
      checkedList: [],
    });

    const state = reactive({
      // 方案评估columns
      tjColumns: [],
      typeList: [],
      optionList: [],
      tableData: [],
      riverList: [],
      siteList: [],
      timeList: {},
      sliderTimeList: {
        startTime: [],
        endTime: [],
      },

      playNumber: "5",
      playType: false,
      interval: "",
      sliderMax: 100,
    });

    const spinning: any = inject("spinning");
    const multipleSelection: any = inject("multipleSelection");

    return {
      searchData,
      ...toRefs(state),
      spinning,
      multipleSelection,
    };
  },
  unmounted() {
    this.deleteInterval();
  },
  watch: {
    multipleSelection: {
      handler(val) {
        setTimeout(() => {
          if (val.length > 0) {
            let mychart = echarts.init(document.getElementById("charts"));
            // mychart.clear();

            // 判断所选成果方案中是否含有长江中下游
            let index = this.multipleSelection.findIndex(
              (item) => item.address === "长江中下游"
            );

            if (index != -1) {
              // 长江中下游暂无方案评估
              this.typeList = [
                {
                  value: "yc",
                  label: "沿程",
                },
                {
                  value: "dd",
                  label: "过程",
                },
              ];
            } else {
              // 非长江中下游
              this.typeList = [
                {
                  value: "yc",
                  label: "沿程",
                },
                {
                  value: "dd",
                  label: "过程",
                },
                {
                  value: "tj",
                  label: "方案评估",
                },
              ];
            }

            this.searchData.showType = "yc";
            this.showTypeChange(this.searchData.showType);
          }
        }, 10);
      },
      deep: true,
    },
  },
  methods: {
    showTypeChange(val) {
      if (val === "yc") {
        let index = this.multipleSelection.findIndex(
          (item) => item.address === "长江中下游"
        );

        if (index != -1) {
          // 长江中下游
          this.optionList = [
            {
              name: "含沙量",
              value: "s",
            },
            {
              name: "流量",
              value: "q",
            },
            {
              name: "冲淤量",
              value: "cy",
            },
          ];
        } else {
          // 非长江中下游
          this.optionList = [
            {
              name: "含沙量",
              value: "s",
            },
            {
              name: "流量",
              value: "q",
            },
            {
              name: "水位",
              value: "z",
            },
            {
              name: "流速",
              value: "uv",
            },
            {
              name: "冲淤量",
              value: "cy",
            },
            // {
            //   name: "过水面积",
            //   value: "a",
            // },
          ];
        }

        this.searchData.type = "s";
        this.getRiver();
      } else if (val === "dd") {
        let index = this.multipleSelection.findIndex(
          (item) => item.address === "长江中下游"
        );

        if (index != -1) {
          // 长江中下游
          this.optionList = [
            {
              name: "含沙量",
              value: "s",
            },
            {
              name: "流量",
              value: "q",
            },
          ];
        } else {
          // 非长江中下游
          this.optionList = [
            {
              name: "含沙量",
              value: "s",
            },
            {
              name: "流量",
              value: "q",
            },
            {
              name: "水位",
              value: "z",
            },
          ];
        }

        this.searchData.type = "s";
        this.getSite();
      } else if (val === "tj") {
        this.optionList = [];
        this.searchData.type = "z";
        this.getRiver();
      }
      this.deleteInterval();

      let mychart = echarts.init(document.getElementById("charts"));
      // mychart.clear();

      setTimeout(() => {
        this.search();
      }, 1000);
    },
    search() {
      this.spinning = true;

      if (this.searchData.showType === "yc") {
        this.ycChartsInit();
      } else if (this.searchData.showType === "dd") {
        this.ddChartsInit();
      } else if (this.searchData.showType === "tj") {
        this.tableData = [];
        if (this.searchData.resultType === "xlqkw") {
          this.getJyDiaodu();
        } else {
          this.getPsDiaodu();
        }
      }
    },
    click() {
      this.$emit("clear");
    },
    /**
     * @description: 沿程图表加载
     * @return {*}
     */
    ycChartsInit() {
      let yName, title;

      title =
        this.timeList[this.searchData.timeSelect].label +
        " " +
        this.searchData.riverNm;

      switch (this.searchData.type) {
        case "z":
          title += "水位沿程线";
          yName = "水位(m)";
          break;
        case "uv":
          title += "流速沿程线";
          yName = "流速(m/s)";
          break;
        case "cy":
          title += "冲淤量沿程线";
          yName = "冲淤量(万m³)";
          break;
        case "a":
          title += "过水面积沿程线";
          yName = "过水面积(㎡)";
          break;
        case "s":
          title += "含沙量沿程线";
          yName = "含沙量(kg/m³)";
          break;
        case "q":
          title += "流量沿程线";
          yName = "流量(m³/s)";
          break;
      }

      let option = {
        title: {
          text: title,
          left: "center",
        },
        legend: {
          data: [],
          top: 20,
        },
        grid: {
          show: true,
          borderWidth: 1,
          borderColor: "#000",
          bottom: 70,
          top: 70,
          left: 50,
          right: 100,
          // containLabel: true,
        },
        tooltip: {
          trigger: "axis",
          hideDelay: 2000,
          backgroundColor: "#fff",
          formatter: (val) => {
            let str = `
              距坝里程：${val[0].name}
              <br />
              断面名称：${val[0].data[2]}
              <br />
            `;
            val.forEach((item) => {
              str += `
                ${item.marker + item.seriesName + "：" + item.data[1]}
                <br />
              `;
            });

            return str;
          },
        },
        dataZoom: {
          show: true,
        },
        xAxis: [
          {
            type: "category",
            name: "距坝里程(KM)",
            splitLine: { show: true },
            inverse: true,
            nameLocation: "start",
            axisLine: {
              show: false,
              onZero: false,
            },
            axisLabel: {
              interval: null,
            },
            axisTick: {
              show: true,
              inside: true,
            },
          },
        ],
        yAxis: {
          type: "value",
          name: yName,
          // boundaryGap:
          //   this.searchData.type === "cy" ? ["0%", "5%"] : ["0%", "5%"],
          axisLine: {
            show: false,
            onZero: false,
          },
          axisTick: {
            show: true,
            inside: true,
          },
          scale: true,
        },
        series: [],
      };

      Promise.all(
        this.multipleSelection.map((item) => {
          option.legend.data.push(item.planName);
          return new Promise<void>((resolve, reject) => {
            if (
              item.state != "计算完成" &&
              item.state != "入库完成" &&
              item.state != "入库失败"
            ) {
              reject();
              return;
            }

            if (item.address != "长江中下游") {
              getAloneLine({
                planno: item.planno,
                area: item.address,
                type: this.searchData.type,
                date: this.timeList[this.searchData.timeSelect].label,
                riverNm: this.searchData.riverNm,
              }).then((res: any) => {
                let obj = {
                  name: item.planName,
                  type: this.searchData.type === "cy" ? "bar" : "line",
                  data: res.data
                    .sort((a, b) => a.rimods - b.rimods)
                    .map((ele) => [ele.rimods, Number(ele.t), ele.stnm]),
                  showSymbol: false,
                };
                if (res.data.length != 0) {
                  option.series.push(obj);
                  option.xAxis.push({
                    type: "category",
                    data: res.data.map(({ stName }) => stName || "").reverse(),
                    axisLine: {
                      show: false,
                      onZero: true,
                    },
                    splitLine: {
                      show: false,
                    },
                    axisTick: {
                      show: false,
                      inside: true,
                    },
                    axisLabel: {
                      interval: 0,
                      margin: -10,
                      verticalAlign: "top",
                      formatter: function (value) {
                        let str = ``;
                        value.split("").forEach((item) => {
                          str += `${item}\n\n`;
                        });
                        return str;
                      },
                    },
                  });
                }
                if (res.data.length > 8) {
                  option.xAxis[0].axisLabel.interval = Math.round(
                    res.data.length / 8
                  );
                  // option.xAxis.forEach(item => {
                  //   item.axisLabel.interval = Math.round(
                  //     res.data.length / 8
                  //   );
                  // })
                } else {
                  option.xAxis[0].axisLabel.interval = "auto";
                  // option.xAxis.forEach(item => {
                  //   item.axisLabel.interval = 'auto'
                  // })
                }
                resolve();
              });
            } else {
              let params: any = {
                planNo: item.planno,
                timeFlag: false,
                section: false,
                type: this.searchData.type,
              };
              if (params.type === "cy") {
                params.startDate =
                  this.timeList[this.searchData.timeSelect].label;
                params.allData = true;
              } else {
                params.time = this.timeList[this.searchData.timeSelect].label;
              }

              readResultFile(params).then((res: any) => {
                if (res.data[0].siteOutQList.length) {
                  res.data[0].siteOutQList = res.data[0].siteOutQList
                    .reverse()
                    .map((item) => {
                      item.mileage = `-${item.mileage}`;
                      return item;
                    });
                }
                if (res.data.length > 8) {
                  option.xAxis.forEach((item) => {
                    item.axisLabel.interval = Math.round(res.data.length / 8);
                  });
                } else {
                  option.xAxis.forEach((item) => {
                    item.axisLabel.interval = "auto";
                  });
                }

                let obj = {
                  name: item.planName,
                  type: "line",
                  data: res.data[0].siteOutQList.map((ele, i) => [
                    ele.mileage,
                    Number(ele.t),
                    ele.siteName,
                  ]),
                  showSymbol: false,
                };
                if (res.data[0].siteOutQList.length != 0) {
                  option.series.push(obj);
                }

                resolve();
              });
            }
          });
        })
      )
        .then(() => {
          let mychart = echarts.init(document.getElementById("charts"));

          mychart.clear();

          setTimeout(() => {
            mychart && mychart.setOption(option);

            setTimeout(() => {
              mychart.resize();
            }, 0);
          }, 1000);
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    /**
     * @description: 过程图表加载
     * @return {*}
     */
    ddChartsInit() {
      let yName, echartsTitle;

      switch (this.searchData.type) {
        case "z":
          yName = "水位(m)";
          echartsTitle = "水位";
          break;
        case "q":
          yName = "流量(m³/s)";
          echartsTitle = "流量";
          break;
        case "s":
          yName = "含沙量(kg/m³)";
          echartsTitle = "含沙量";
          break;
      }

      let option = {
        title: {
          text: this.searchData.stcd + echartsTitle + "过程线",
          left: "center",
        },
        legend: {
          data: [],
          top: 20,
        },
        tooltip: {
          trigger: "axis",
          hideDelay: 2000,
          backgroundColor: "#fff",
        },
        grid: {
          show: true,
          borderWidth: 1,
          borderColor: "#000",
          bottom: 50,
          top: 50,
          left: 50,
          right: 60,
          containLabel: true,
        },
        dataZoom: {
          show: true,
        },
        xAxis: {
          type: "time",
          name: "日期",
          splitLine: { show: true },
          axisLine: {
            show: false,
          },
          axisLabel: {
            formatter: (value) => {
              return moment(value).format("YY-MM-DD HH");
            },
          },
          axisTick: {
            show: true,
            inside: true,
          },
        },
        yAxis: {
          type: "value",
          name: yName,
          axisLine: {
            show: false,
          },
          axisTick: {
            show: true,
            inside: true,
          },
          scale: true,
        },
        series: [],
      };

      Promise.all(
        this.multipleSelection.map((item) => {
          option.legend.data.push(item.planName);
          return new Promise<void>((resolve) => {
            if (item.address != "长江中下游") {
              getSingleAttribute({
                planno: item.planno,
                area: item.address,
                type: this.searchData.type,
                stcd: this.searchData.stcd,
              }).then((res: any) => {
                for (const key in res[this.searchData.stcd]) {
                  if (key.includes("data")) {
                    let obj = {
                      name:
                        key === "data2"
                          ? `${item.planName}预报数据`
                          : item.planName,
                      type: "line",
                      data: res[this.searchData.stcd][key].map((item) => [
                        moment(
                          moment(item[0]).format("YYYY-MM-DD HH")
                        ).valueOf(),
                        item[1],
                      ]),
                      symbol: "none",
                      lineStyle: {
                        type: key === "data2" ? "dashed" : "solid",
                      },
                    };
                    if (res[this.searchData.stcd].data.length != 0) {
                      option.series.push(obj);
                    }

                    if (key === "data2") {
                      option.legend.data.push(`${item.planName}预报数据`);
                    }
                  }
                }

                resolve();
              });
            } else {
              // 长江中下游
              readResultFile({
                type: this.searchData.type,
                timeFlag: false,
                planNo: item.planno,
                section: false,
                siteName: this.searchData.stcd,
              }).then((res: any) => {
                let echartData = [];
                for (const key in res.data) {
                  echartData.push([
                    moment(key).format("YYYY-MM-DD HH"),
                    res.data[key],
                  ]);
                }
                let obj = {
                  name: item.planName,
                  type: "line",
                  data: echartData,
                  symbol: "none",
                  lineStyle: {
                    type: "solid",
                  },
                };

                if (Object.keys(res.data).length != 0) {
                  option.series.push(obj);
                }

                resolve();
              });
            }
          });
        })
      )
        .then(() => {
          let arr = [];
          for (const key in this.timeList) {
            arr.push(this.timeList[key]);
          }

          Promise.all(
            this.searchData.checkedList.map((ele) => {
              option.legend.data.push(ele);

              if (ele === "报汛数据") {
                return new Promise<void>((resolve) => {
                  validateReal({
                    type: this.searchData.type,
                    stcd: this.searchData.stcd,
                    startTime: arr[0].label,
                    endTime: arr[arr.length - 1].label,
                  })
                    .then((res: any) => {
                      if (res.data.length != 0) {
                        let obj = {
                          name: "报汛数据",
                          type: "line",
                          data: res.data.map((item) => [
                            moment(
                              moment(item[0]).format("YYYY-MM-DD HH")
                            ).valueOf(),
                            item[1],
                          ]),
                          symbol: "none",
                        };

                        option.series.push(obj);
                      }
                    })
                    .finally(() => {
                      resolve();
                    });
                });
              } else {
                return new Promise<void>((resolve) => {
                  validateZB({
                    type: this.searchData.type,
                    stcd: this.searchData.stcd,
                    startTime: arr[0].label,
                    endTime: arr[arr.length - 1].label,
                  })
                    .then((res: any) => {
                      if (res.data.length != 0) {
                        let obj = {
                          name: "整编数据",
                          type: "line",
                          data: res.data.map((item) => [
                            moment(
                              moment(item[0]).format("YYYY-MM-DD HH")
                            ).valueOf(),
                            item[1],
                          ]),
                          symbol: "none",
                        };

                        option.series.push(obj);
                      }
                    })
                    .finally(() => {
                      resolve();
                    });
                });
              }
            })
          ).finally(() => {
            let mychart = echarts.init(document.getElementById("charts"));

            mychart.clear();

            mychart && mychart.setOption(option);

            setTimeout(() => {
              mychart.resize();
            }, 0);
          });
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    playNumberChange(type) {
      let num = parseFloat(this.playNumber);
      if (type === "add") {
        num += 1;
      } else {
        if (num > 1) {
          num -= 1;
        }
      }
      this.playNumber = num;
      this.playStart(this.playType);
    },
    playStart(type) {
      if (!type) {
        return;
      }
      this.playType = true;
      this.deleteInterval();

      this.interval = setInterval(() => {
        // let index = this.timeList.findIndex(
        //   (item) => item === this.searchData.timeSelect
        // );
        // if (index + 1 === this.timeList.length) {
        //   index = -1;
        // }
        // this.searchData.timeSelect = this.timeList[index + 1];

        this.ycChartsInit();
      }, this.playNumber * 1000);
    },
    deleteInterval(type) {
      clearInterval(this.interval);
      this.interval = null;
      if (type) {
        this.playType = false;
      }
    },
    /**
     * @description: 获取方案成果时间
     * @return {*}
     */
    getRiver() {
      let timeArr = [];

      Promise.all(
        this.multipleSelection.map((item) => {
          return new Promise<void>((resolve, reject) => {
            if (item.address != "长江中下游") {
              getAloneLine({
                planno: item.planno,
                area: item.address,
                type: this.searchData.type,
              }).then((res: any) => {
                this.riverList = res.name;
                this.searchData.riverNm = res.name[0];
                res.time.shift();
                timeArr = timeArr.concat(res.time);

                resolve();
              });
            } else {
              readResultFile({
                planNo: item.planno,
                timeFlag: true,
                section: false,
                type: this.searchData.type,
              }).then((res: any) => {
                this.riverList = ["长江"];
                this.searchData.riverNm = "长江";
                timeArr = timeArr.concat(res.data);

                resolve();
              });
            }
          });
        })
      )
        .then(() => {
          // 获取到的时间进行处理 去重=>排序=>按照拖动条数据格式处理
          this.timeList = Array.from(new Set(timeArr))
            .sort((a, b) => moment(a).valueOf() - moment(b).valueOf())
            .map((item) => {
              return {
                style: {
                  display: "none",
                },
                label: item,
              };
            });

          this.sliderTimeList.startTime = this.timeList[0].label.split(" ");
          this.sliderTimeList.endTime =
            this.timeList[this.timeList.length - 1].label.split(" ");

          this.sliderMax = this.timeList.length;

          if (this.timeList.length === 0) {
            ElMessage.error("所选成果暂无对比时间");
            this.searchData.timeSelect = "";
          } else {
            this.searchData.timeSelect = 0;
            this.searchData.tjTime = [0, this.timeList.length - 1];
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    /**
     * @description: 获取过程站点
     * @return {*}
     */
    getSite() {
      let siteArr = [];

      Promise.all(
        this.multipleSelection.map((item) => {
          return new Promise<void>((resolve, reject) => {
            if (item.address != "长江中下游") {
              // 非长江中下游
              getSingleAttribute({
                planno: this.multipleSelection[0].planno,
                area: this.multipleSelection[0].address,
                type: this.searchData.type,
              }).then((res: any) => {
                siteArr = siteArr.concat(res.name);

                resolve();
              });
            } else {
              // 长江中下游
              readResultFile({
                type: this.searchData.type,
                timeFlag: false,
                planNo: item.planno,
                section: true,
              }).then((res: any) => {
                siteArr = siteArr.concat(res.data);

                resolve();
              });
            }
          });
        })
      ).then(() => {
        this.siteList = Array.from(new Set(siteArr));
        this.searchData.stcd = this.siteList[0];
      });
    },
    /**
     * @description: 获取消落期库尾减淤数据
     * @return {*}
     */
    getJyDiaodu() {
      // 判断所选时间是否正确（目前弃用）
      if (this.searchData.tjTime.length != 2) {
        this.spinning = false;
        ElMessage.error("请选择两个时间");
        return;
      }

      let startTime = this.timeList[this.searchData.tjTime[0]].label;
      let endTime = this.timeList[this.searchData.tjTime[1]].label;

      if (this.searchData.tjTime[0] > this.searchData.tjTime[1]) {
        startTime = this.timeList[this.searchData.tjTime[1]].label;
        endTime = this.timeList[this.searchData.tjTime[0]].label;
      }
      // ——————————————

      let obj = {
        // startTime: startTime,
        // endTime: endTime,
        plannos: this.multipleSelection
          .map((item) => {
            return item.planno;
          })
          .join(","),
      };

      getJyDiaoDuList(obj)
        .then((res: any) => {
          if (res) {
            if (this.searchData.resultShowType === "table") {
              // 生成表格表头数据
              this.tjColumns = [
                {
                  title: "方案名称",
                  dataIndex: "name",
                  align: "center",
                },
                {
                  title: "冲淤量(万m³)",
                  children: [],
                },
              ];

              this.tjColumns[1].children = res[0].arr.map((item) => {
                return {
                  title: item,
                  dataIndex: item,
                  align: "center",
                };
              });

              // 处理获取到的数据
              this.tableData = res.map((item) => {
                for (const key in item.data) {
                  if (key != "name") {
                    item.data[key] = (Number(item.data[key]) / 10000).toFixed(
                      3
                    );
                  }
                }
                return item.data;
              });
            } else {
              const elem = document.getElementById("tjBarEcharts");

              elem.removeAttribute("_echarts_instance_");

              let myChart = echarts.getInstanceByDom(elem);

              if (myChart == undefined) {
                myChart = echarts.init(elem);
              }

              const option = {
                tooltip: {
                  trigger: "axis",
                  axisPointer: {
                    type: "shadow",
                  },
                },
                legend: {},
                grid: {
                  bottom: 10,
                  top: 50,
                  left: 28,
                  right: 10,
                  containLabel: true,
                },
                xAxis: {
                  type: "category",
                  data: res[0].arr,
                  axisLabel: {
                    fontSize: 14,
                  },
                },
                yAxis: {
                  name: "冲淤量(万m³)",
                  type: "value",
                },
                label: {
                  show: true,
                  position: "top",
                },
                series: res.map((item) => {
                  return {
                    name: item.data.name,
                    type: "bar",
                    data: item.arr.map((ele) =>
                      (Number(item.data[ele]) / 10000).toFixed(3)
                    ),
                  };
                }),
              };

              myChart.setOption(option);
            }
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    /**
     * @description:获取汛期沙峰排沙
     * @return {*}
     */
    getPsDiaodu() {
      // 判断所选时间是否正确（目前弃用）
      if (this.searchData.tjTime.length != 2) {
        this.spinning = false;
        ElMessage.error("请选择两个时间");
        return;
      }

      let startTime = this.timeList[this.searchData.tjTime[0]].label;
      let endTime = this.timeList[this.searchData.tjTime[1]].label;

      if (this.searchData.tjTime[0] > this.searchData.tjTime[1]) {
        startTime = this.timeList[this.searchData.tjTime[1]].label;
        endTime = this.timeList[this.searchData.tjTime[0]].label;
      }
      // ——————————————

      let obj = {
        // startTime: startTime,
        // endTime: endTime,
        plannos: this.multipleSelection
          .map((item) => {
            return item.planno;
          })
          .join(","),
      };

      getPsDiaoDuList(obj)
        .then((res: any) => {
          if (res) {
            if (this.searchData.resultShowType === "table") {
              // 生成表头数据
              this.tjColumns = [
                {
                  title: "方案名称",
                  dataIndex: "name",
                  align: "center",
                },
                {
                  title: "冲淤量(万m³)",
                  children: [],
                },
                {
                  title: "入库沙量(万吨)",
                  dataIndex: "入库沙量",
                  align: "center",
                },
                {
                  title: "出库沙量(万吨)",
                  dataIndex: "排沙量",
                  align: "center",
                },
                {
                  title: "排沙比(%)",
                  dataIndex: "排沙比",
                  align: "center",
                },
              ];

              this.tjColumns[1].children = res[0].arr.map((item) => {
                return {
                  title: item,
                  dataIndex: item,
                  align: "center",
                };
              });

              // 处理获得的数据
              this.tableData = res.map((item) => {
                for (const key in item.data) {
                  if (key != "name") {
                    item.data[key] = Number(item.data[key]).toFixed(3);
                  }
                }
                return item.data;
              });
            } else {
              const elem = document.getElementById("tjBarEcharts");

              elem.removeAttribute("_echarts_instance_");

              let myChart = echarts.getInstanceByDom(elem);

              if (myChart == undefined) {
                myChart = echarts.init(elem);
              }

              const option = {
                tooltip: {
                  trigger: "axis",
                  axisPointer: {
                    type: "shadow",
                  },
                },
                legend: {},
                grid: {
                  bottom: 10,
                  top: 50,
                  left: 10,
                  right: 10,
                  containLabel: true,
                },
                xAxis: {
                  type: "category",
                  data: res[0].arr,
                  axisLabel: {
                    fontSize: 14,
                  },
                },
                yAxis: {
                  name: "冲淤量(万m³)",
                  type: "value",
                },
                label: {
                  show: true,
                  position: "top",
                },
                series: res.map((item) => {
                  return {
                    name: item.data.name,
                    type: "bar",
                    data: item.arr.map((ele) => item.data[ele]),
                  };
                }),
              };

              myChart.setOption(option);
            }
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    tjTimeChange(val, arr) {
      if (this.searchData.tjTime.length > 2) {
        this.searchData.tjTime.shift();
      }
    },
    /**
     * @description: 成果导出按钮
     * @return {*}
     */
    exportBtn() {
      let mychart = echarts.init(document.getElementById("charts"));

      let obj = {
        // 获取图表数据后根据数据生成导出所需数组
        dataList: mychart.getOption().series[0].data.map((item) => {
          return {
            // 判断显示类型
            [this.searchData.showType === "yc" ? "rimods" : "dt"]: item[0],
            t: item[1].toString(),
            stnm: item[2],
          };
        }),
        riverNm: "",
        yname: "",
        time: this.searchData.timeSelect,
        name: "",
      };

      switch (this.searchData.type) {
        case "z":
          obj.yname = "水位";
          break;
        case "uv":
          obj.yname = "流速";
          break;
        case "cy":
          obj.yname = "冲淤量";
          break;
        case "a":
          obj.yname = "过水面积";
          break;
        case "s":
          obj.yname = "含沙量";
          break;
        case "q":
          obj.yname = "流量";
          break;
        default:
          obj.yname = this.searchData.type;
          break;
      }

      if (this.searchData.showType === "yc") {
        obj.riverNm = this.searchData.riverNm;
        obj.name =
          obj.riverNm + " " + obj.yname + " " + obj.time + " " + "沿程线数据";
        exportwriteexcel(obj).then((res) => {});
      } else {
        delete obj.time;
        obj.riverNm = this.searchData.stcd;
        obj.name = obj.riverNm + " " + obj.yname + " " + "过程线数据";
        ycwriteexcel(obj).then((res) => {});
      }
    },
    formatTooltip(val) {
      if (Object.keys(this.timeList).length != 0)
        return moment(this.timeList[val].label).format("YYYY-MM-DD HH:00:00");
    },
  },
});
</script>

<style scoped lang="less">
.form {
  position: relative;
  height: 100%;
  border: 1px solid #ccc;
  border-radius: 15px;
  padding: 15px;
  margin-right: 15px;
  overflow: hidden;
  box-sizing: border-box;

  .btn {
    position: absolute;
    bottom: 15px;
    right: 25px;
  }

  .exportBtn {
    position: absolute;
    bottom: 15px;
    right: 100px;
  }

  .check-item {
    margin: 0;
    margin-right: 5px;
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 250px;
  }
}

.ant-table-striped :deep(.table-striped) {
  background-color: #fafafa;
}

.close {
  cursor: pointer;
  position: absolute;
  z-index: 2000;
  right: 460px;
  font-size: 24px;
}
</style>
